#!/usr/bin/env python
# coding: utf-8

# In[118]:


from elasticsearch import Elasticsearch
import pandas as pd
es = Elasticsearch(hosts='106.13.117.37', port='9200')


# In[119]:


body = {
    "query":{
        "match_all":{}
    }
}
data1 = pd.DataFrame([i['_source'] for i in es.search(index='movieinfo',body=body,size=13000).get('hits').get('hits')])


# In[120]:


data1.head(5)


# In[121]:


data1['month'] = [i[:7] for i in data1['date']]


# In[122]:


data1.head(5)


# In[123]:


import datetime,time


# In[124]:


ll = []
for name,value in data1.groupby('month'):
    sell = value['boxOffice'].sum()
    temp = name + '-01 00:00:00'
    ll.append({'time':time.mktime(datetime.datetime.strptime(temp,'%Y-%m-%d %H:%M:%S').timetuple()),'sell':sell})


# In[125]:


ll = pd.DataFrame(ll)


# In[126]:


ll.head(5)


# In[127]:


import numpy as np
np.random.seed(1337)
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Activation
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import Dense


# In[128]:


X = ll['time']
Y = ll['sell']
x_train,x_test,y_train,y_test = train_test_split(X,Y,test_size=0.2, random_state=42)


# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[129]:


neurons = 128 
activation_function = 'tanh'   # 激活函数
loss = 'mse'  # 损失函数
optimizer="adam"  # 优化函数      
dropout = 0.01


# In[130]:


model = Sequential()
 
model.add(LSTM(neurons, return_sequences=True, input_shape=(1, 1), activation=activation_function))
model.add(Dropout(dropout))
model.add(LSTM(neurons, return_sequences=True, activation=activation_function))
model.add(Dropout(dropout))
model.add(LSTM(neurons, activation=activation_function))
model.add(Dropout(dropout))
model.add(Dense(output_dim=1, input_dim=1))
#
model.compile(loss=loss, optimizer=optimizer)


# In[131]:


# training 训练
print('Training -----------')
epochs = 1000
for step in range(epochs):
    cost = model.train_on_batch(x_train[:, np.newaxis, np.newaxis], y_train)
    if step % 30 == 0:
        print(f'{step} train cost: ', cost)


# In[132]:


# 测试
print('Testing ------------')
cost = model.evaluate(x_test[:, np.newaxis, np.newaxis], x_test, batch_size=2)
print('test cost:', cost)


# In[133]:


# 打印预测结果
Y_pred = model.predict(x_test[:, np.newaxis, np.newaxis])
# plt.scatter(y_test, y_test)
plt.plot(x_test, Y_pred, 'ro')
plt.show()


# In[134]:


Y_pred*38727399.16986828


# In[135]:


y_test


# In[136]:


plt.plot(X,Y)


# In[137]:


from dateutil import relativedelta
current = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y-%m")
print(current)
current += '-01 00:00:00'


# In[138]:


pre = []
for i in range(1,4):
    pre.append(time.mktime((datetime.datetime.strptime(current,'%Y-%m-%d %H:%M:%S')+relativedelta.relativedelta(months=i)).timetuple()))


# In[139]:


model.predict(pd.Series(pre)[:, np.newaxis, np.newaxis])*38727399.16986828


# In[140]:


model.predict(ll['time'][:, np.newaxis, np.newaxis])*38727399.16986828


# In[142]:


model.save(r'C:\Users\l\Desktop\final-progect\boxoffice.h5')


# In[ ]:




